package com.macrosoftinc.feedreaderxtreme.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.WeakHashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.macrosoft.frpd.bo.FeedItem;
import com.macrosoft.frpd.bo.ResponseStatus;
import com.macrosoft.frpd.parser.FenopyParser;
import com.macrosoft.frpd.parser.ParserFactory;
import com.macrosoft.frpd.parser.ParserFactory.PARSERS;
import com.macrosoft.frpd.parser.helper.IPublishResultListener;
import com.macrosoft.frpd.parser.helper.PublishResultHelper;
import com.macrosoft.frpd.parser.helper.SortBy;
import com.macrosoft.frpd.parser.helper.TorrentFeedBO;
import com.macrosoft.frpd.utils.Logger;
import com.macrosoft.frpd.utils.Logger.DebugLevel;
import com.macrosoftinc.feedreaderxtreme.FeedReaderXtremeApplication;
import com.macrosoftinc.feedreaderxtreme.R;
import com.macrosoftinc.feedreaderxtreme.adapter.CustomFragmentPagerAdapter;
import com.macrosoftinc.feedreaderxtreme.adapter.CustomTorrentsListAdapter;
import com.macrosoftinc.feedreaderxtreme.adapter.TorrentTypesExpandableAdapter;
import com.macrosoftinc.feedreaderxtreme.anim.CustomAnimatedBaseActivty;
import com.macrosoftinc.feedreaderxtreme.anim.ExpandAnimation;
import com.macrosoftinc.feedreaderxtreme.bean.TorrentType;
import com.macrosoftinc.feedreaderxtreme.bean.TorrentTypeChild;
import com.macrosoftinc.feedreaderxtreme.fragments.CategoriesDetailFragment;
import com.macrosoftinc.feedreaderxtreme.util.DataUtil;
import com.macrosoftinc.feedreaderxtreme.widget.RefreshableListView;
import com.macrosoftinc.feedreaderxtreme.widget.RefreshableListView.OnRefreshListener;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.SlidingMenu.CanvasTransformer;

public class HomeActivity extends CustomAnimatedBaseActivty implements IPublishResultListener {

	private static final String SHARED_FILE_NAME = "shared.png";

	ViewPager viewPager;
	private LinearLayout getCategoriesWaitDialog = null;
	private ArrayList<TorrentType> leftMenuTorrentType;

	private FenopyParser parser = null;
	CustomFragmentPagerAdapter adapterOftorrentsOfCategory;
	WeakHashMap<String, List<TorrentFeedBO>> hashMapOfTorrents;
	List<FeedItem> catFeedItems;

	boolean[] optionsForRefreshList;
	MenuItem refreshMenuItem;
	MenuItem shareMenuItem;
	MenuItem sortByDate;
	MenuItem sortByPeers;
	MenuItem sortBySeeders;
	MenuItem sortByLeachers;
	MenuItem sortBySize;
	SearchView searchView;
	Menu mMenu = null;
	List<SortBy> mSortByList = null;
	private int currentSelectedCategory = 0;

	boolean latestTop;

	// private RelativeLayout getTorrentsOfCategoryDialog;

	String shareTitle = "Share Test";
	String shareUrl = "Share Url";

	boolean loadMore;

	public HomeActivity() {
		// see the class CustomAnimation for how to attach
		// the CanvasTransformer to the SlidingMenu
		super(R.string.app_name, new CanvasTransformer() {
			@Override
			public void transformCanvas(Canvas canvas, float percentOpen) {
				canvas.scale(percentOpen, 1, 0, 0);
			}
		});
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Logger.i("onCreate()" + this.getClass().getSimpleName());
		initializeScreen();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// Logger.i(this.getClass().getSimpleName() + "-----onDestroy()");
		PublishResultHelper.getInstance().addPublishListener(null);
		PublishResultHelper.setmHelper(null);
		hashMapOfTorrents = null;
		catFeedItems = null;
		parser = null;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Logger.i("newConfig=====" + newConfig);
		updateConfigurationChanges();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// Logger.i("onResume()" + this.getClass().getSimpleName());
		initializeLeftMenu();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Logger.i("onCreateOptionsMenu()" + this.getClass().getSimpleName());
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.activity_home, (Menu) menu);
		mMenu = menu;
		shareMenuItem = menu.findItem(R.id.share);
		refreshMenuItem = menu.findItem(R.id.refresh);
		sortByDate = menu.findItem(R.id.sort_by_date);
		sortByPeers = menu.findItem(R.id.sort_by_peers);
		sortBySeeders = menu.findItem(R.id.sort_by_seeders);
		sortByLeachers = menu.findItem(R.id.sort_by_leechers);
		sortBySize = menu.findItem(R.id.sort_by_size);

		menu.setGroupVisible(R.id.sort_by_group, false);
		// Get the provider and hold onto it to set/change the share intent.
		// ShareActionProvider shareActionProvider = (ShareActionProvider) ;
		// Set the default share intent
		// shareActionProvider.setShareIntent(getDefaultShareIntent());
		((ShareActionProvider) shareMenuItem.getActionProvider()).setShareIntent(createShareIntent());
		((ShareActionProvider) shareMenuItem.getActionProvider()).setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);

		MenuItem searchViewMenuItem = menu.findItem(R.id.search);
		searchView = (SearchView) searchViewMenuItem.getActionView();
		searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextChange(String newText) {
				// Do nothing
				// Logger.i("onQueryTextChange==" + newText);
				refreshListAdapterBySearchCriteria(viewPager.getCurrentItem(), newText);
				return true;
			}

			@Override
			public boolean onQueryTextSubmit(String query) {
				// Clear SearchView
				searchView.clearFocus();
				// Logger.i("onQueryTextSubmit" + query);
				refreshListAdapterBySearchCriteria(viewPager.getCurrentItem(), query);
				return true;
			}
		});

		if (adapterOftorrentsOfCategory == null)
			getCategoriesOfTorrentType(0, 0);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (isSortByAvailable()) {
			menu.setGroupVisible(R.id.sort_by_group, true);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Logger.i("onOptionsItemSelected()" + this.getClass().getSimpleName());
		switch (item.getItemId()) {
		case R.id.refresh:
			// runRefresh();
			if (refreshMenuItem != null && refreshMenuItem.getActionView() == null) {
				// runActionBarRefresh();
				getCategoriesOfTorrentType(0, 0);
			}
			break;
		case R.id.share:
			// startActivity(Intent.createChooser(getDefaultShareIntent(), getString(R.string.share_this_string)));
			startActivity(Intent.createChooser(createShareIntent(), getString(R.string.share_this_string)));
			break;
		case R.id.sort_by_date:
			item.setCheckable(true);

			getTorrentsOfSelectedCategoryWithUrl(currentSelectedCategory, mSortByList.get(SortBy.INDEX_DATE).sortByUrl);

			break;

		case R.id.sort_by_leechers:
			item.setChecked(true);

			getTorrentsOfSelectedCategoryWithUrl(currentSelectedCategory, mSortByList.get(SortBy.INDEX_LEECHERS).sortByUrl);

			break;

		case R.id.sort_by_peers:
			item.setChecked(true);

			getTorrentsOfSelectedCategoryWithUrl(currentSelectedCategory, mSortByList.get(SortBy.INDEX_PEERS).sortByUrl);

			break;
		case R.id.sort_by_seeders:
			item.setChecked(true);

			getTorrentsOfSelectedCategoryWithUrl(currentSelectedCategory, mSortByList.get(SortBy.INDEX_SEEDERS).sortByUrl);

			break;

		case R.id.sort_by_size:
			item.setChecked(true);
			getTorrentsOfSelectedCategoryWithUrl(currentSelectedCategory, mSortByList.get(SortBy.INDEX_Size).sortByUrl);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void updateConfigurationChanges() {
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
	}

	private void initializeScreen() {
		// Logger.i("initializeScreen called" + this.getClass().getSimpleName());
		setContentView(R.layout.activity_home);

		getCategoriesWaitDialog = (LinearLayout) findViewById(R.id.progress_bar_layout);
		PublishResultHelper.getInstance().addPublishListener(HomeActivity.this);
		catFeedItems = new ArrayList<FeedItem>();
		hashMapOfTorrents = new WeakHashMap<String, List<TorrentFeedBO>>();
		DataUtil.copyPrivateRawResuorceToPubliclyAccessibleFile(this, SHARED_FILE_NAME);
		parser = (FenopyParser) ParserFactory.getParserFor(this, PARSERS.FENOPY);
		viewPager = (ViewPager) findViewById(R.id.activity_main_pager);
		viewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr);
		viewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width));
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// Logger.i("onPageScrolledStateChanged Called" + arg0);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// Logger.i("onPageScrolled called");
			}

			@Override
			public void onPageSelected(int position) {
				// Logger.i("onPageSelected      position=" + position);
				currentSelectedCategory = position;
				searchView.clearFocus();
				// searchView.setQuery("", true);
				if (hashMapOfTorrents.containsKey(catFeedItems.get(position).getTitle()) && hashMapOfTorrents.get(catFeedItems.get(position).getTitle()) == null) {
					// Logger.i("pnPageSelected Condition True");
					getTorrentsOfSelectedCategory(position);
					adapterOftorrentsOfCategory.getFragments().get(position).showTorrentItemsProgressDialog();
				} else {
					// Logger.i("pnPageSelected Condition false");
					// (CategoriesDetailFragment) ;
					adapterOftorrentsOfCategory.getFragments().get(position).setItems(hashMapOfTorrents.get(catFeedItems.get(position).getTitle()));
					adapterOftorrentsOfCategory.getFragments().get(position).updateTorrentListAdpater(loadMore);
				}
				switch (position) {
				case 0:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
					break;
				default:
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
					break;
				}
			}

		});
	}

	private void initializeLeftMenu() {
		ExpandableListView expandList = (ExpandableListView) mFrag.getView().findViewById(android.R.id.list);
		leftMenuTorrentType = getListItems();
		expandList.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				toggle();
				getCategoriesOfTorrentType(groupPosition, childPosition);
				return false;
			}
		});
		TorrentTypesExpandableAdapter torrentTypesExpandableAdapter = new TorrentTypesExpandableAdapter(this, leftMenuTorrentType);
		expandList.setAdapter(torrentTypesExpandableAdapter);
	}

	private void runActionBarRefresh() {
		if (refreshMenuItem != null && refreshMenuItem.getActionView() == null) {
			LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			ImageView iv = (ImageView) inflater.inflate(R.layout.nav_refresh_image_layout, null);
			Animation rotation = AnimationUtils.loadAnimation(this, R.anim.title_bar_progress_animation);
			rotation.setRepeatCount(Animation.INFINITE);
			iv.startAnimation(rotation);
			refreshMenuItem.setActionView(iv);
		}
	}

	protected void stopActionBarRefresh() {
		if (refreshMenuItem != null && refreshMenuItem.getActionView() != null) {
			refreshMenuItem.getActionView().clearAnimation();
			refreshMenuItem.setActionView(null);
		}
		// hideTorrentProgressDialog();
	}

	private Intent getDefaultShareIntent() {
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.setType("image/*");
		Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
		shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
		return shareIntent;
	}

	private Intent createShareIntent() {
		// Intent shareIntent = new Intent(Intent.ACTION_SEND);
		// shareIntent.setType("image/plain*");
		// Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
		// shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
		// shareIntent.putExtra(Intent.EXTRA_TITLE, currentSelectedUrl);
		// shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, currentSelectedUrl);
		// shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, currentSelectedUrl);

		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.setType("image/*");
		Uri uri = Uri.fromFile(getFileStreamPath("shared.png"));
		shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
		shareIntent.putExtra(Intent.EXTRA_TITLE, shareTitle + " : " + shareUrl);
		shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareTitle);
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareUrl);

		return shareIntent;
	}

	private void setCategoriesFragmentsList(List<FeedItem> pItems) {
		if (pItems.size() > 0) {
			if (catFeedItems != null)
				catFeedItems.clear();
			catFeedItems = pItems;
			hashMapOfTorrents = new WeakHashMap<String, List<TorrentFeedBO>>();
			optionsForRefreshList = new boolean[pItems.size()];
			for (int i = 0; i < catFeedItems.size(); i++) {
				hashMapOfTorrents.put(catFeedItems.get(i).getTitle(), null);
			}

			// To destroy cached previous fragments
			destroyPreviousFragmentsFromBackStack();
			adapterOftorrentsOfCategory = new CustomFragmentPagerAdapter(getSupportFragmentManager(), catFeedItems);

			Log.i(this.getClass().getSimpleName(),
					"after---- setCategoriesFragmentsList------adapterOftorrentsOfCategory.getFragments().size()" + adapterOftorrentsOfCategory.getFragments());

			viewPager.setAdapter(adapterOftorrentsOfCategory);
			viewPager.getAdapter().notifyDataSetChanged();
			if (!(catFeedItems.size() <= 0)) {
				getTorrentsOfSelectedCategory(0);
				adapterOftorrentsOfCategory.getFragments().get(0).showTorrentItemsProgressDialog();
			}
		} else {
			viewPager.setBackgroundColor(Color.WHITE);
		}
	}

	private void destroyPreviousFragmentsFromBackStack() {
		if (adapterOftorrentsOfCategory != null && adapterOftorrentsOfCategory.getFragments() != null) {
			Log.i(this.getClass().getSimpleName(),
					"before --- setCategoriesFragmentsList------adapterOftorrentsOfCategory.getFragments().size()" + adapterOftorrentsOfCategory.getFragments());
			for (Fragment fragment : adapterOftorrentsOfCategory.getFragments()) {
				FragmentManager manager = ((Fragment) fragment).getFragmentManager();
				FragmentTransaction trans = manager.beginTransaction();
				trans.remove((Fragment) fragment);
				trans.commit();
			}
		}
	}

	private void showGetCategoriesWaitDialog() {
		if (getCategoriesWaitDialog != null)
			getCategoriesWaitDialog.setVisibility(ProgressBar.VISIBLE);
	}

	private void hideGetCategoriesWaitDialog() {
		if (getCategoriesWaitDialog != null)
			getCategoriesWaitDialog.setVisibility(ProgressBar.GONE);
	}

	private ArrayList<TorrentType> getListItems() {
		ArrayList<TorrentType> groupList = new ArrayList<TorrentType>();
		TorrentType group = new TorrentType("Fenopy", R.drawable.fenopy_icon);
		ArrayList<TorrentTypeChild> list = new ArrayList<TorrentTypeChild>();
		list.add(new TorrentTypeChild("XML Feeds", parser.getXMLFeedMainCategoryURL(), R.drawable.fenopy_icon));
		list.add(new TorrentTypeChild("Verified Torrents", parser.getVerifiedFeedMainCategoryURL(), R.drawable.fenopy_icon));
		list.add(new TorrentTypeChild("Browse All", parser.URL_BASE_FENOPY, R.drawable.fenopy_icon));
		group.setItems(list);
		groupList.add(group);
		return groupList;
	}

	private void refreshListAdapterBySearchCriteria(int catPosition, String searchCriteria) {
		// Logger.i("searchCriteria===" + searchCriteria);
		if (catFeedItems != null && catFeedItems.size() > 0) {
			List<TorrentFeedBO> items = hashMapOfTorrents.get(catFeedItems.get(catPosition).getTitle());
			List<TorrentFeedBO> listOfRefinedItems = new ArrayList<TorrentFeedBO>();
			for (TorrentFeedBO item : items) {
				// Logger.i("item title before find===" + item.title);

				if (item.title.toLowerCase().contains(searchCriteria.toLowerCase())) {
					// Logger.i("Find===" + item.title);
					listOfRefinedItems.add(item);
				}
			}
			((CategoriesDetailFragment) adapterOftorrentsOfCategory.getItem(catPosition)).setListAdapter(new CustomTorrentsListAdapter(this, R.layout.torrent_detail_list_item,
					R.id.torrent_title, listOfRefinedItems));
		}
	}

	private boolean isNextPageUrlExist(int position) {
		if (hashMapOfTorrents.get(catFeedItems.get(position).getTitle()).size() > 0) {
			TorrentFeedBO lastItem = hashMapOfTorrents.get(catFeedItems.get(position).getTitle()).get(hashMapOfTorrents.get(catFeedItems.get(position).getTitle()).size() - 1);
			if (lastItem.nextPageURL != null)
				return true;
		}
		return false;
	}

	private void updateTorrentsDetailScreen(final int catPosition, List<TorrentFeedBO> items) {
		// Logger.i("updateTorrentsDetailScreen called catPosition===" + catPosition);
		// final CategoriesDetailFragment catDetailFragment = (CategoriesDetailFragment) adapterOftorrentsOfCategory.getItem(catPosition);
		final CategoriesDetailFragment catDetailFragment = (CategoriesDetailFragment) adapterOftorrentsOfCategory.getFragments().get(catPosition);
		catDetailFragment.setItems(items);
		catDetailFragment.updateTorrentListAdpater(loadMore);
		catDetailFragment.setLatestTopLayoutState();
		catDetailFragment.hideTorrentItemsProgressDialog();
		final RefreshableListView refreshableListView = (RefreshableListView) catDetailFragment.getListView();
		refreshableListView.setCatPositionList(catPosition);
		refreshableListView.setLoadMoreState(isNextPageUrlExist(catPosition));
		refreshableListView.getmLoadMoreButton().setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Logger.i("load more clicked  catPosition===" + catPosition);
				loadMore = true;
				getTorrentsOfSelectedCategoryNextPageUrl(catPosition);
				refreshableListView.setLoadMoreButtonVisbility(View.GONE);
				optionsForRefreshList[catPosition] = true;
			}
		});
		if (catDetailFragment.getLatestTopLayout() != null) {
			catDetailFragment.getLatestTopLayout().findViewById(R.id.latest_torrent_id).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// Logger.i("//////------latest torrent clicked");
					latestTop = true;
					getTorrentsOfSelectedCategoryWithUrl(catPosition, (String) v.getTag());
				}
			});
			catDetailFragment.getLatestTopLayout().findViewById(R.id.top_torrent_id).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// Logger.i("//////------top torrent clicked");
					latestTop = true;
					getTorrentsOfSelectedCategoryWithUrl(catPosition, (String) v.getTag());
				}
			});
		}
		refreshableListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh(RefreshableListView listView, int position) {
				// TODO Auto-generated method stub
				// Logger.i("onrefreshPosition position===" + position);
				getTorrentsOfSelectedCategory(position);
				optionsForRefreshList[position] = true;
			}
		});
		refreshableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {

				View toolbar = view.findViewById(R.id.toolbar);

				final TorrentFeedBO selectedItem = (TorrentFeedBO) ((HeaderViewListAdapter) parent.getAdapter()).getWrappedAdapter().getItem(position); // catDetailFragment.getItems().get(position);

				// Logger.i("item click position===" + position + "---------selectedItem===" + selectedItem.title);
				// Creating the expand animation for the item
				ExpandAnimation expandAni = new ExpandAnimation(toolbar, 500);
				// Start the animation on the toolbar
				toolbar.startAnimation(expandAni);
				toolbar.findViewById(R.id.list_item_download_button_id).setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						shareUrl = selectedItem.downloadURL;
						shareTitle = selectedItem.title;
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.addCategory(Intent.CATEGORY_DEFAULT);
						i.setData(Uri.parse(shareUrl));
						// i.setType("application/x-bittorrent");
						if (DataUtil.isTorrentIntentAvailable(view.getContext(), i)) {
							startActivity(i);
						} else {
							Toast.makeText(view.getContext(), "No Activity found to handle this Intent", Toast.LENGTH_LONG).show();
						}
					}
				});

				toolbar.findViewById(R.id.list_item_share_button_id).setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						shareUrl = selectedItem.downloadURL;
						shareTitle = selectedItem.title;
						((ShareActionProvider) shareMenuItem.getActionProvider()).setShareIntent(createShareIntent());
						startActivity(Intent.createChooser(createShareIntent(), getString(R.string.share_this_string)));
					}
				});
			}
		});
		if (optionsForRefreshList[catPosition] == true) {
			refreshableListView.completeRefreshing();
			catDetailFragment.getListView().completeLoading();
			optionsForRefreshList[catPosition] = false;
		}
	}

	private void getCategoriesOfTorrentType(int groupPosition, int childPosition) {
		try {
			String url = leftMenuTorrentType.get(groupPosition).getItems().get(childPosition).getUrl();
			if (!parser.isUrlDownloadingDataInProcess(url)) {
				parser.parseMainCategory(childPosition, url);
				showGetCategoriesWaitDialog();
				shareUrl = leftMenuTorrentType.get(groupPosition).getItems().get(childPosition).getUrl();
				shareTitle = leftMenuTorrentType.get(groupPosition).getItems().get(childPosition).getTorrentTypeChildName();
				((ShareActionProvider) shareMenuItem.getActionProvider()).setShareIntent(createShareIntent());
				runActionBarRefresh();
				Toast.makeText(HomeActivity.this, "URL called====" + url, Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			Logger.log(this.getClass().getCanonicalName(), e);
		}
	}

	private void getTorrentsOfSelectedCategory(int categoryPosition) {
		// Logger.i("getTorrentsOfSelectedCategory called categoryPosition===" + categoryPosition + "------catFeedItems.get(categoryPosition).getURL()=="
		// + catFeedItems.get(categoryPosition).getURL());
		try {
			if (catFeedItems.get(categoryPosition).getURL().contains(".xml"))
				((FenopyParser) parser).parseTorrentFeed(categoryPosition, catFeedItems.get(categoryPosition).getURL());
			else
				((FenopyParser) parser).parseHTMLTorrents(categoryPosition, catFeedItems.get(categoryPosition).getURL());

			shareUrl = catFeedItems.get(categoryPosition).getURL();
			shareTitle = catFeedItems.get(categoryPosition).getTitle();

			((ShareActionProvider) shareMenuItem.getActionProvider()).setShareIntent(createShareIntent());

			// runActionBarRefresh();

			Toast.makeText(FeedReaderXtremeApplication.getAppContext(), "URL called====" + catFeedItems.get(categoryPosition).getURL(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Logger.log(DebugLevel.WARNING, "", e);
		}
	}

	private void getTorrentsOfSelectedCategoryWithUrl(int categoryPosition, String url) {
		// Logger.i("getTorrentsOfSelectedCategory called categoryPosition===" + categoryPosition + "------catFeedItems.get(categoryPosition).getURL()==" + url);
		try {
			if (url.contains(".xml"))
				((FenopyParser) parser).parseTorrentFeed(categoryPosition, url);
			else
				((FenopyParser) parser).parseHTMLTorrents(categoryPosition, url);

			shareUrl = url;
			shareTitle = catFeedItems.get(categoryPosition).getTitle();

			((ShareActionProvider) shareMenuItem.getActionProvider()).setShareIntent(createShareIntent());

			// runActionBarRefresh();
			Toast.makeText(FeedReaderXtremeApplication.getAppContext(), "URL called====" + catFeedItems.get(categoryPosition).getURL(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Logger.log(DebugLevel.WARNING, "", e);
		}
	}

	private void getTorrentsOfSelectedCategoryNextPageUrl(int categoryPosition) {
		try {
			// Logger.i("hashMapOfTorrents.get(categoryPosition).size()=" + hashMapOfTorrents.get(catFeedItems.get(categoryPosition).getTitle()).size());

			TorrentFeedBO lastItem = hashMapOfTorrents.get(catFeedItems.get(categoryPosition).getTitle()).get(
					hashMapOfTorrents.get(catFeedItems.get(categoryPosition).getTitle()).size() - 1);
			if (lastItem.nextPageURL != null) {

				// Logger.i("lastItem====" + lastItem.title + "-----lastItem.nextPageURL" + lastItem.nextPageURL);

				// Logger.i("Next Page Url===" + lastItem.nextPageURL + "--------categoryPosition=" + categoryPosition);
				if (catFeedItems.get(categoryPosition).getURL().contains(".xml"))
					((FenopyParser) parser).parseTorrentFeed(categoryPosition, lastItem.nextPageURL);
				else
					((FenopyParser) parser).parseHTMLTorrents(categoryPosition, lastItem.nextPageURL);

				shareUrl = catFeedItems.get(categoryPosition).getURL();
				shareTitle = catFeedItems.get(categoryPosition).getTitle();
				((ShareActionProvider) shareMenuItem.getActionProvider()).setShareIntent(createShareIntent());

				// runActionBarRefresh();
				// showWaitTorrentProgressDialog();
				Toast.makeText(FeedReaderXtremeApplication.getAppContext(), "URL called====" + catFeedItems.get(categoryPosition).getURL(), Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			Logger.log(DebugLevel.WARNING, "", e);
		}
	}

	@Override
	public void publishResultCategoryHTML(int torrenType, ResponseStatus status, List<FeedItem> pItem) {
		// TODO Auto-generated method stub
		// Logger.i("publishResultCategoryHTML******torrenType==" + torrenType + "      ResponseStatus==" + status.isCallSuccessful() + "    pItem.size()+=" + pItem.size());
		stopActionBarRefresh();
		hideGetCategoriesWaitDialog();
		setCategoriesFragmentsList(pItem);
	}

	@SuppressLint("NewApi")
	@Override
	public void publishResultFeedXML(int selectedCategoryPosition, ResponseStatus status, List<TorrentFeedBO> mResultList) {

		// Logger.i("publishResultFeedXML******selectedCategory==" + selectedCategoryPosition + "      ResponseStatus==" + status.isCallSuccessful());
		// Logger.i("publishResultFeedXML******selectedCategory==" + selectedCategoryPosition + "    pItem.size()+=" + mResultList.size());
		// Logger.i("publishResultFeedXML******selectedCategory==" + selectedCategoryPosition + "    catFeedItems.get(selectedCategoryPosition).getTitle()="
		// + catFeedItems.get(selectedCategoryPosition).getTitle());
		try {
			this.mSortByList = mResultList.get(mResultList.size() - 1).sortByList;
			if (isSortByAvailable()) {
				this.invalidateOptionsMenu();
			}
		} catch (NullPointerException npe) {
			Logger.log(DebugLevel.WARNING, "", npe);
		} catch (IndexOutOfBoundsException ioe) {
			Logger.log(DebugLevel.WARNING, "", ioe);
		}

		// stopActionBarRefresh();
		// if (hashMapOfTorrents.containsKey(catFeedItems.get(selectedCategoryPosition).getTitle())
		// && (hashMapOfTorrents.get(catFeedItems.get(selectedCategoryPosition).getTitle()) != null) && loadMore) {
		// mResultList.addAll(hashMapOfTorrents.get(catFeedItems.get(selectedCategoryPosition).getTitle()));
		// }

		hashMapOfTorrents.put(catFeedItems.get(selectedCategoryPosition).getTitle(), mResultList);
		updateTorrentsDetailScreen(selectedCategoryPosition, mResultList);
		loadMore = false;
	}

	private boolean isSortByAvailable() {
		return this.mSortByList != null && this.mSortByList.size() > 0;
	}
}
